import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:largefriends/config/lf_route.dart';
import 'package:largefriends/net/error_handle.dart';
import 'package:largefriends/service/lf_auth_service.dart';
import 'package:largefriends/utils/lf_dialog_utils.dart';

import '../../../config/lf_config.dart';
import '../../../res/strings/lf_strings.dart';
import '../../../utils/lf_keyboard.dart';
import '../../../widgets/dialog_action_tip.dart';

enum EditTextType {
  headline('headline'),
  aboutMe("about"),
  aboutMatch("matchAbout");

  final String value;

  const EditTextType(this.value);
}

toEditTextPage({required EditTextType type}) {
  Get.toNamed(LFRoute.pathEditText, arguments: {'type': type});
}

class LfEditTextLogic extends GetxController {
  LfAuthService authService = Get.find();
  RxString content = "".obs;
  RxString hint = "".obs;
  String origin = "";
  String title = "";
  int maxNum = 255;
  int minNum = 10;
  FocusNode focusNode = FocusNode();
  TextEditingController controller = TextEditingController();
  late EditTextType type;
  @override
  void onInit() {
    type = Get.arguments['type'];
    if (type == EditTextType.aboutMe) {
      content.value = authService.currentAccount!.about ?? "";
      hint.value = strAboutMeTip.tr;
      title = strAboutMe.tr;
      maxNum = maxAboutMe;
      minNum = minAboutMe;
    } else if (type == EditTextType.aboutMatch) {
      content.value = authService.currentAccount!.matchAbout ?? "";
      hint.value = strAboutMyMatchTip.tr;
      title = strAboutMyMatch.tr;
      maxNum = maxAboutMatch;
      minNum = minAboutMatch;
    } else if (type == EditTextType.headline) {
      content.value = authService.currentAccount!.headline ?? "";
      hint.value = strHeadlineTip.tr;
      title = strHeadline.tr;
      maxNum = maxHeadline;
      minNum = minHeadline;
    }
    origin = content.value.trim();
    controller.text = content.value;
    super.onInit();
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  void onBackPress() {
    closeSoftKeyboard();
    if (content.value.trim() != origin.trim() &&
        content.value.trim().isNotEmpty) {
      showActionTips(
          tips: strDiscardChange.tr,
          actionButtonTip: strSure.tr,
          action: () {
            Get.back();
          });
    } else {
      Get.back();
    }
  }

  void save() async {
    closeSoftKeyboard();
    showLoading();
    await authService.updateUserProfile(
        data: {"user[${type.value}]": content}).then((value) {
      hideLoading();
      Get.back();
    }, onError: (err) {
      hideLoading();
      if (err is NetError) {
        showSnackBar(err.msg);
      }
    });
  }

  @override
  void onClose() {
    controller.dispose();
    focusNode.dispose();
    super.onClose();
  }
}
